﻿#region Using

using System;
using System.Net;
using System.Text;
using WSMon.Core.Configuration;
using WSMon.Core.Helpers;
using WSMon.Core.Interfaces;

#endregion

namespace WSMon.Core.Checkers.Web
{
    public class SourceCodeChecker : Checker, IChecker
    {
        private readonly SourceCodeConfiguration _sourceCodeConfig;
        private string _logs = string.Empty;

        public SourceCodeChecker(SourceCodeConfiguration sourceCodeConfig)
        {
            if (sourceCodeConfig == null)
                throw new ArgumentNullException("sourceCodeConfig");

            _sourceCodeConfig = sourceCodeConfig;
        }

        #region IChecker Members

        public bool CheckOut()
        {
            try
            {
                string sourceCode = HttpRequestHelper.GetSourceCode(_sourceCodeConfig.HttpRequestConfig.Url,
                                                                    new NetworkCredential(
                                                                        _sourceCodeConfig.HttpRequestConfig.UserName,
                                                                        _sourceCodeConfig.HttpRequestConfig.Password),
                                                                    Encoding.UTF8);

                if (_sourceCodeConfig.BlackWords != null)
                {
                    foreach (var blackWord in _sourceCodeConfig.BlackWords)
                    {
                        if (sourceCode.Contains(blackWord))
                            throw new Exception(string.Format("Source code contains bad word:{0}", blackWord));
                    }
                }

                if (_sourceCodeConfig.WhiteWords != null)
                {
                    foreach (var whiteWord in _sourceCodeConfig.WhiteWords)
                    {
                        if (!sourceCode.Contains(whiteWord))
                            throw new Exception(string.Format("Source code does not contains white word:{0}", whiteWord));
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                _logs = ex.Message;
                return false;
            }
        }

        public string GetLogs()
        {
            return _logs;
        }

        #endregion
    }
}